package team.pra.manager.common.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import team.pra.manager.mapper.AuthorityMapper;
import team.pra.manager.pojo.Authority;
import team.pra.manager.pojo.SysToken;
import team.pra.manager.pojo.User;
import team.pra.manager.service.ShiroService;

import java.time.LocalDateTime;
import java.util.List;
@Component
public class AuthRealm extends AuthorizingRealm {
    @Autowired
    private ShiroService shiroService;
    @Autowired(required = false)
    private AuthorityMapper authorityMapper;
    final static Logger logger = LoggerFactory.getLogger(AuthRealm.class);
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("enter authorizationinfo");
        User user = (User)principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(user.getRole().getName());
        logger.info("euthorizationInfo---{}",user.getRole().getName());
        List<Authority> authorities = authorityMapper.findAllPermission(user.getRole().getId());
        for (Authority authority : authorities) {
            info.addStringPermission(authority.getPermission().getUrl());
        }
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取前端传进来的token
        String token = (String) authenticationToken.getPrincipal();
        //验证token
        SysToken sysToken = shiroService.findByToken(token);
        if (sysToken == null || sysToken.getExpireTime().isBefore(LocalDateTime.now())) {
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }
        User user = shiroService.findByUserId(sysToken.getUserId());
        if (user == null) {
            throw new UnknownAccountException("用户不存在!");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, token, this.getName());
        return info;
    }
}
